package com.example.demo.service.impl;

import com.example.demo.service.EventPublishService;
import com.google.gson.Gson;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/5/16.
 */
@Service
public class EventPublishServiceImpl implements EventPublishService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public List<Map<String, Object>> selectAllDataByNew() {
        return jdbcTemplate.queryForList("select * from transaction_eventPublish where status = 'new'");
    }

    /**
     * 开启事务，并保持幂等性（入过此坑）
     * @param lists
     * @return
     */
    @Override
    @Transactional(rollbackFor=Exception.class)
    public int updateStatus(List<Map<String,Object>> lists){
        rabbitTemplate.setChannelTransacted(true);
        int rv = 0;
        for (Map<String,Object> maps : lists) {
            rv = jdbcTemplate.update("UPDATE transaction_eventPublish SET status = 'published' WHERE status = 'new'");
            if (rv > 0) {
                rabbitTemplate.convertAndSend("hello", maps);
            }
        }
        //throw new RuntimeException("sss");
        return rv;
    }
}
